package com.realife.eson.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;

/**
 * Mybatis plus Handler配置类
 * 处理一些公共字段
 *
 * @author zgc
 */
@Slf4j
@Component
public class CommonMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        //this.setFieldValByName("createdTime", new Date(), metaObject);
        //this.setFieldValByName("updatedTime", new Date(), metaObject);


        /**
         *
         */
        String[] setterNames = metaObject.getSetterNames();
        Arrays.stream(setterNames).forEach(System.out::println);

        log.info("start insert fill ....");
        this.strictInsertFill(metaObject, "isDeleted", Integer.class, 0); // 起始版本 3.3.0(推荐使用)
        this.strictInsertFill(metaObject, "version", Integer.class, 1); // 起始版本 3.3.0(推荐使用)
        this.strictInsertFill(metaObject, "createdTime", Date.class, new Date()); // 起始版本 3.3.0(推荐使用)
        this.strictInsertFill(metaObject, "updatedTime", Date.class, new Date()); // 起始版本 3.3.0(推荐使用)

        if (metaObject.hasSetter("author")) {
            System.out.println("has author...");
        } else {
            System.out.println("not has author...");
        }


        Object isDeleted = getFieldValByName("isDeleted", metaObject);
        //业务层没给数据,则自动填充,否则什么也不干...
        if (null == isDeleted) {
            strictInsertFill(metaObject, "isDeleted", Integer.class, 0);
        }
    }



    @Override
    public void updateFill(MetaObject metaObject) {
        //this.setFieldValByName("updatedTime", new Date(), metaObject);

        /**
         *
         */
        String[] setterNames = metaObject.getSetterNames();
        Arrays.stream(setterNames).forEach(System.out::println);

        log.info("start update fill ....");
        this.strictUpdateFill(metaObject, "updatedTime", Date.class, new Date()); // 起始版本 3.3.0(推荐)

        if (metaObject.hasSetter("author")) {
            System.out.println("has author...");
        } else {
            System.out.println("not has author...");
        }

    }


}
